﻿using BaseUI;
using BLL;
using System;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;
using Utility.Helper;

namespace Thksoft.Module.BillManagement
{
    public partial class BankBillsLedger : BasePage
    {
        private BankBillsLedgerBLL bll = new BankBillsLedgerBLL();
        protected string filePath = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindBank();

                FORM_BEGIN_DATE.Value = "";

                FORM_OVER_DATE.Value = "";

                ViewState["SortOrder"] = "T2.N_ID";
                ViewState["OrderDire"] = " ASC ";

                BindData(true);
            }
        }

        private void Bind()
        {
            string whereStr = "";
            //出票账号
            if (txtDRAWERACCOUNT.Value.Trim() != "")
            {
                whereStr += " AND ACCOUNT LIKE '%" + txtDRAWERACCOUNT.Value.Trim() + "%'";
            }
            //票据种类
            if (FORM_Type.SelectedValue != "-1")
            {
                whereStr += " AND TYPE =" + Convert.ToDecimal(FORM_Type.SelectedValue.ToString());
            }
            //出票公司
            if (FORM_COMPANY_ID.Value != -1)
            {
                /*whereStr += @"  and DE_COMPANY_ID in (select cp.cmy_id
  from sys_company cp
 start with cp.cmy_id = " + FORM_COMPANY_ID.Value + @"
connect by prior cp.cmy_id = cp.cmy_parentid) ";*/
                whereStr += " and DE_COMPANY_ID=" + FORM_COMPANY_ID.Value;
            }
            else
            {
                whereStr += @"  and DE_COMPANY_ID in (select cp.cmy_id
  from sys_company cp
 start with cp.cmy_id = " + lognUser.USER_COMPANY + @"
connect by prior cp.cmy_id = cp.cmy_parentid) ";
            }

            //出票银行
            if (FORM_BANK_ID.SelectedValue != "-1")
            {
                whereStr += " AND DE_BANK_ID = " + Convert.ToDecimal(FORM_BANK_ID.SelectedValue.ToString());
            }

            //票据日期
            if (FORM_BEGIN_DATE.Value.Trim() != "" && FORM_OVER_DATE.Value.Trim() != "")
            {
                whereStr += @" and START_DATE between
       TO_DATE('" + FORM_BEGIN_DATE.Value + @"', 'YYYY-MM-DD') and
       TO_DATE('" + FORM_OVER_DATE.Value + @"', 'YYYY-MM-DD') ";
            }

            ViewState["Where"] = whereStr;

            BindData(true);
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSelect_Click(object sender, EventArgs e)
        {
            Bind();
        }

        protected void grvShow1_Sorting(object sender, GridViewSortEventArgs e)
        {
            //点击排序
            string sPage = e.SortExpression;

            if (sPage == "")
            {
                return;
            }
            if (ViewState["SortOrder"].ToString() == sPage)
            {
                if (ViewState["OrderDire"].ToString() == "Desc")
                    ViewState["OrderDire"] = "ASC";
                else
                    ViewState["OrderDire"] = "Desc";
            }
            else
            {
                ViewState["SortOrder"] = e.SortExpression;
                ViewState["OrderDire"] = "ASC";
            }

            BindData(true);
        }

        private void BindData(bool isFirst)
        {
            string Where = "";
            try
            {
                Where = ViewState["Where"].ToString();
            }
            catch
            {
                Where = " and DE_COMPANY_ID=" + FORM_COMPANY_ID.Value;
            }

            int rowcount = 0;
            if (isFirst)
            {
                PageIng.CurrentPage = 1;
            }
            rowcount = bll.GetRecordCount(Where);

            string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];

            DataTable dt = bll.GetListByPage2(Where, sort, PageIng.CurrentPage, PageIng.RowsPerPage);

            var row = dt.NewRow();
            row["N_ID"] = DBNull.Value;
            row["TYPENAME"] = "合计";
            row["CMY_NAME"] = DBNull.Value;
            row["C_NAME"] = DBNull.Value;
            row["ACCOUNT"] = DBNull.Value;
            row["PAY_AMOUNT"] = dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["PAY_AMOUNT"]));
            row["START_DATE"] = DBNull.Value;
            row["DE_CODE"] = DBNull.Value;
            row["REMARK"] = DBNull.Value;
            dt.Rows.Add(row);

            ViewState["database"] = dt;
            //Session["datatable"] = dt;
            if (dt.Rows.Count > 0)
            {
                PageIng.Visible = true;
                PageIng.RowsCount = rowcount;
                PageIng.DataSource = dt;
                PageIng.GridViewSource = grvShow1;
                PageIng.RowsPerPage = PageIng._rowsPerPage;
                PageIng.Bind();
            }
            else
            {
                PageIng.DataSource = dt;
                PageIng.GridViewSource = grvShow1;
                grvShow1.DataSource = null;
                grvShow1.DataBind();
                PageIng.Visible = false;
            }
            //导出
            BindPint();
        }

        protected void PageIng_DataBinding(object sender, EventArgs e)
        {
            BindData(false);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //protected void btnEdit_Click(object sender, EventArgs e)
        //{
        //    int count = 0;
        //    for (int i = 0; i < grvShow1.Rows.Count; i++)
        //    {
        //        if (((CheckBox)grvShow1.Rows[i].FindControl("chkSelectId")).Checked == true)
        //        {
        //            count++;
        //            if (count == 1)
        //            {
        //                string pid = ((CheckBox)grvShow1.Rows[i].FindControl("chkSelectId")).ToolTip;
        //                string billid = grvShow1.Rows[i].Cells[0].Text.ToString();
        //                MessageBox.ResponseScript(this, "FORM_EDIT(" + billid + "," + pid + ");");
        //                return;
        //            }
        //        }
        //    }
        //}

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDaoChu_Click(object sender, EventArgs e)
        {
            var BANK = "";
            //出票银行
            if (FORM_BANK_ID.SelectedValue != "-1")
            {
                BANK = FORM_BANK_ID.SelectedItem.Text.ToString();
            }

            var ACCOUNT = "";
            //出票账号
            if (txtDRAWERACCOUNT.Value.Trim() != "")
            {
                ACCOUNT = txtDRAWERACCOUNT.Value.Trim();
            }
            var dt = (DataTable)ViewState["database"];

            #region 导出一

            //dt.Columns["R"].ColumnName = "序号";
            //dt.Columns["TYPENAME"].ColumnName = "票据种类";
            //dt.Columns["CMY_NAME"].ColumnName = "汇款公司名称";
            //dt.Columns["C_NAME"].ColumnName = "汇款银行";
            //dt.Columns["ACCOUNT"].ColumnName = "汇款账号";
            //dt.Columns["C_PAYEECMYNAME"].ColumnName = "收款公司名称";
            //dt.Columns["C_PAYEEBANKNAME"].ColumnName = "收款银行";
            //dt.Columns["C_PAYEEACCOUNT"].ColumnName = "收款账号";
            //dt.Columns["FS_NUMBER"].ColumnName = "份数";
            //dt.Columns["USER_NAME"].ColumnName = "出票人";
            //dt.Columns["C_DRAWEENAME"].ColumnName = "付款人";
            //dt.Columns["PAYEENAME"].ColumnName = "收款人";
            //dt.Columns["PAY_AMOUNT"].ColumnName = "汇款金额";
            //dt.Columns["START_DATE"].ColumnName = "出票日期";
            //dt.Columns["D_ENDDATE"].ColumnName = "最后日期";
            //dt.Columns["DE_CODE"].ColumnName = "票据编号";
            //dt.Columns["N_IFOFFER"].ColumnName = "能否转让";
            ////dt.Columns["REMARK"].ColumnName = "承兑信息";
            //dt.Columns["N_PAYTYPE"].ColumnName = "支付类型";
            //dt.Columns["C_PAYEENUMBER"].ColumnName = "收款人联系电话";
            //dt.Columns["N_TERMOFBILL"].ColumnName = "票据期限（月）";
            //dt.Columns["D_ACCEPTANCETIME"].ColumnName = "承兑时间";
            //dt.Columns["D_COLLECTTICKETSTIME"].ColumnName = "收票时间";
            //dt.Columns["C_PROJECTNAME"].ColumnName = "项目名称（用途）";
            //dt.Columns["C_PROJECTCODE"].ColumnName = "交易合同号（用途）";

            dt.Columns.Remove("CMY_NAME");
            dt.Columns.Remove("C_NAME");
            dt.Columns.Remove("ACCOUNT");
            //dt.Columns.Remove("C_PAYEECMYNAME");
            dt.Columns.Remove("C_PAYEEBANKNAME");
            dt.Columns.Remove("C_PAYEEACCOUNT");
            dt.Columns.Remove("C_DRAWEENAME");
            dt.Columns.Remove("REMARK");

            dt.Columns.Remove("TYPE");
            dt.Columns.Remove("ID");
            dt.Columns.Remove("DE_COMPANY_ID");
            dt.Columns.Remove("DE_BANK_ID");
            dt.Columns.Remove("N_ID");
            dt.Columns.Remove("N_TYPE");
            dt.Columns.Remove("N_DRAWERUSERID");
            dt.Columns.Remove("N_BILL_ID");
            //toExecl1(dt, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "银行票据台账");

            #endregion 导出一

            filePath = ToExecl(BANK, ACCOUNT, dt, "票据台账明细", "银行票据台账");

            Response.Redirect(filePath);
        }

        protected void BindPint()
        {
            DataTable temp = (DataTable)ViewState["database"];
            string InerHtmls = "";

            var bank = "";
            if (FORM_BANK_ID.SelectedValue != "-1")
            {
                bank = FORM_BANK_ID.SelectedItem.Text;
            }

            if (temp != null && temp.Rows.Count > 0)
            {
                InerHtmls += "<table border='1' style='border-collapse:collapse;'>";
                InerHtmls += @"<tr style='height: 40px; mso-height-source: userset; mso-height-alt: 600;'>
                            <th align='center' class='xl70' height='40' width='1945' colspan='18' style='height: 30.00pt;
                                width: 1458.75pt;border: .5pt solid windowtext;' x:str=''>
                                银行票据台账
                            </th>
                            </tr>";
                InerHtmls += @"<tr height='40' style='height: 30.00pt; mso-height-source: userset; mso-height-alt: 600;'><td colspan='18' style='border: .5pt solid windowtext;'><td></tr>";

                InerHtmls += @"<tr height='40' class='xl65' style='height: 30.00pt; mso-height-source: userset;mso-height-alt: 600;'>
                            <td class='xl74' colspan='18' style='border: .5pt solid windowtext;' x:str=''>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                开户行：" + bank + @"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                账号：" + txtDRAWERACCOUNT.Value.Trim() + @"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            </td>
                        </tr>";

                InerHtmls += @" <tr height='40' class='xl66' style='height: 30.00pt; mso-height-source: userset;mso-height-alt: 600;'>
                            <td class='xl75' height='120' rowspan='3' style='width: 16px; height: 90.00pt; border: .5pt solid windowtext; ' x:str=''>
                                序号
                            </td>
                            <td class='xl75' rowspan='3' style='width: 100px; border: .5pt solid windowtext;' x:str=''>
                                票据种类
                            </td>
                            <td class='xl75' colspan='3' style='border: .5pt solid windowtext;'x:str=''>
                                购入情况
                            </td>
                            <td class='xl75' colspan='12' style='border: .5pt solid windowtext;'x:str=''>
                                使用情况
                            </td>
                            <td class='xl75' rowspan='3' style='width: 100px; border: .5pt solid windowtext;' x:str=''>
                                承兑时间
                            </td>
                        </tr>";

                InerHtmls += @"<tr height='40' class='xl66' style='height: 30.00pt; mso-height-source: userset;mso-height-alt: 600;'>
                            <td class='xl75' rowspan='2' style='width: 100px; border: .5pt solid windowtext;' x:str=''>
                                日&nbsp;&nbsp;&nbsp;&nbsp;期
                            </td>
                            <td class='xl75' rowspan='2' style='width: 100px; border: .5pt solid windowtext;' x:str=''>
                                票据号码
                            </td>
                            <td class='xl75' rowspan='2' style='width: 15px; border: .5pt solid windowtext;' x:str=''>
                                份数
                            </td>
                            <td class='xl75' rowspan='2' style='width: 100px; border: .5pt solid windowtext;' x:str=''>
                                出票日期
                            </td>
                            <td class='xl76' rowspan='2' style='width: 100px; border: .5pt solid windowtext;' x:str=''>
                                票据期限（月）
                            </td>
                            <td class='xl75' rowspan='2' style='width: 100px; border: .5pt solid windowtext;' x:str=''>
                                到期日
                            </td>
                            <td class='xl75' rowspan='2' style='width: 100px; border: .5pt solid windowtext;' x:str=''>
                                票据号码
                            </td>
                            <td class='xl75' rowspan='2' style='width: 100px; border: .5pt solid windowtext;' x:str=''>
                                收款单位
                            </td>
                            <td class='xl75' colspan='2' style='border: .5pt solid windowtext;'x:str=''>
                                用&nbsp;&nbsp;&nbsp;&nbsp;途
                            </td>
                            <td class='xl81' rowspan='2' style='width: 100px; border: .5pt solid windowtext;' x:str=''>
                                金额(元）
                            </td>
                            <td class='xl82' rowspan='2' style='width: 100px; border: .5pt solid windowtext;' x:str=''>
                                经办人
                            </td>
                            <td class='xl82' rowspan='2' style='width: 100px; border: .5pt solid windowtext;' x:str=''>
                                收票时间
                            </td>
                            <td class='xl82' rowspan='2' style='width: 100px; border: .5pt solid windowtext;' x:str=''>
                                收票人签字
                            </td>
                            <td class='xl75' rowspan='2' style='width: 100px; border: .5pt solid windowtext;' x:str=''>
                                收票人联系电话
                            </td>
                        </tr>";

                InerHtmls += @"<tr height='40' class='xl66' style='height: 30.00pt; mso-height-source: userset;mso-height-alt: 600;'>
                            <td class='xl75' style='width: 100px;'>
                                项目名称
                            </td>
                            <td class='xl75' style='width: 100px;'>
                                合同编号
                            </td>
                        </tr>";
                for (int i = 0; i < temp.Rows.Count; i++)
                {
                    InerHtmls += "<tr height='40' style='height: 30.00pt; mso-height-source: userset; mso-height-alt: 600;'>";
                    InerHtmls += "<td class='xl77' style='width:15px;'>" + temp.Rows[i]["R"].ToString() + "</td>";
                    InerHtmls += "<td class='xl77' style='width:100px;'>" + temp.Rows[i]["TYPENAME"].ToString() + "</td>";
                    InerHtmls += "<td class='xl78' style='width:100px;'>" + temp.Rows[i]["D_PURCHASEDATE"].DateFormat("yyyy-MM-dd") + "</td>";
                    InerHtmls += "<td class='xl78' style='width:100px;'>" + temp.Rows[i]["DE_CODE"].ToString() + "</td>";
                    InerHtmls += "<td class='xl77' style='width:15px;'>" + temp.Rows[i]["FS_NUMBER"].ToString() + "</td>";
                    InerHtmls += "<td class='xl78' style='width:100px;'>" + temp.Rows[i]["START_DATE"].DateFormat("yyyy-MM-dd") + "</td>";
                    InerHtmls += "<td class='xl79' style='width:100px;'>" + temp.Rows[i]["N_TERMOFBILL"].ToString() + "</td>";
                    InerHtmls += "<td class='xl78' style='width:100px;'>" + temp.Rows[i]["D_ENDDATE"].DateFormat("yyyy-MM-dd") + "</td>";
                    InerHtmls += "<td class='xl78' style='width:100px;'>" + temp.Rows[i]["DE_CODE"].ToString() + "</td>";
                    InerHtmls += "<td class='xl78' style='width:100px;'>" + temp.Rows[i]["C_PAYEECMYNAME"].ToString() + "</td>";
                    InerHtmls += "<td class='xl78' style='width:100px;'>" + temp.Rows[i]["C_PROJECTNAME"].ToString() + "</td>";
                    InerHtmls += "<td class='xl78' style='width:100px;'>" + temp.Rows[i]["C_PROJECTCODE"].ToString() + "</td>";
                    InerHtmls += "<td class='xl83' style='width:100px;'>" + temp.Rows[i]["PAY_AMOUNT"].ToString() + "</td>";
                    InerHtmls += "<td class='xl84' style='width:100px;'>" + temp.Rows[i]["USER_NAME"].ToString() + "</td>";
                    InerHtmls += "<td class='xl78' style='width:100px;'>" + temp.Rows[i]["D_COLLECTTICKETSTIME"].DateFormat("yyyy-MM-dd") + "</td>";
                    InerHtmls += "<td class='xl84' style='width:100px;'>" + temp.Rows[i]["PAYEENAME"].ToString() + "</td>";
                    InerHtmls += "<td class='xl77' style='width:100px;'>" + temp.Rows[i]["C_PAYEENUMBER"].ToString() + "</td>";
                    InerHtmls += "<td class='xl77' style='width:100px;'>" + temp.Rows[i]["D_ACCEPTANCETIME"].DateFormat("yyyy-MM-dd") + "</td>";
                    InerHtmls += "</tr>";
                }
                InerHtmls += "</table>";
            }
            this.Div1.InnerHtml = InerHtmls;//HtmlTableRow
        }

        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void PRINT_CLICK(object sender, EventArgs e)
        {
            var key = Guid.NewGuid().ToString();
            Session[key] = Div1.InnerHtml;//Area:[\"1500px\",\"800px\"],Scrollbar:true})
            MessageBox.ResponseScript(Page, "top.MessageBox.Print({Value:\"ID=HTML&VALUE=" + key + "\",Area:[\"900px\",\"700px\"],Scrollbar:true})");

            #region 打印1

            //try
            //{
            //    var key = Guid.NewGuid().ToString();
            //    Session[key + "Header"] = "银行票据台账";

            //    var dt = ((DataTable)ViewState["database"]).Copy();

            //    dt.Columns.Remove("C_DRAWEENAME");
            //    dt.Columns.Remove("USER_NAME");
            //    dt.Columns.Remove("C_PAYEEACCOUNT");
            //    dt.Columns.Remove("C_PAYEEBANKNAME");
            //    dt.Columns.Remove("C_PAYEECMYNAME");
            //    dt.Columns.Remove("C_PROJECTCODE");
            //    dt.Columns.Remove("C_PROJECTNAME");
            //    dt.Columns.Remove("D_COLLECTTICKETSTIME");
            //    dt.Columns.Remove("D_ACCEPTANCETIME");
            //    dt.Columns.Remove("N_TERMOFBILL");
            //    dt.Columns.Remove("C_PAYEENUMBER");
            //    dt.Columns.Remove("N_IFOFFER");
            //    dt.Columns.Remove("D_ENDDATE");
            //    dt.Columns.Remove("N_PAYTYPE");

            //    dt.Columns.Remove("TYPE");
            //    dt.Columns.Remove("ID");
            //    dt.Columns.Remove("DE_COMPANY_ID");
            //    dt.Columns.Remove("DE_BANK_ID");
            //    dt.Columns.Remove("N_ID");
            //    dt.Columns.Remove("N_TYPE");
            //    dt.Columns.Remove("N_DRAWERUSERID");
            //    dt.Columns.Remove("N_BILL_ID");
            //    for (int i = 0; i < dt.Columns.Count; i++)
            //    {
            //        if (dt.Columns[i].ColumnName.Trim().ToString() == "R")
            //        {
            //            dt.Columns[i].ColumnName = "序号";
            //        }
            //        if (dt.Columns[i].ColumnName.Trim().ToString() == "TYPENAME")
            //        {
            //            dt.Columns[i].ColumnName = "票据种类";
            //        }
            //        if (dt.Columns[i].ColumnName.Trim().ToString() == "CMY_NAME")
            //        {
            //            dt.Columns[i].ColumnName = "出票公司名称";
            //        }
            //        if (dt.Columns[i].ColumnName.Trim().ToString() == "C_NAME")
            //        {
            //            dt.Columns[i].ColumnName = "出票银行名称";
            //        }
            //        if (dt.Columns[i].ColumnName.Trim().ToString() == "ACCOUNT")
            //        {
            //            dt.Columns[i].ColumnName = "支付账号";
            //        }
            //        if (dt.Columns[i].ColumnName.Trim().ToString() == "PAYEENAME")
            //        {
            //            dt.Columns[i].ColumnName = "收款人";
            //        }
            //        if (dt.Columns[i].ColumnName.Trim().ToString() == "PAY_AMOUNT")
            //        {
            //            dt.Columns[i].ColumnName = "金额";
            //        }
            //        if (dt.Columns[i].ColumnName.Trim().ToString() == "START_DATE")
            //        {
            //            dt.Columns[i].ColumnName = "出票时间";
            //        }
            //        if (dt.Columns[i].ColumnName.Trim().ToString() == "DE_CODE")
            //        {
            //            dt.Columns[i].ColumnName = "票据编号";
            //        }
            //        if (dt.Columns[i].ColumnName.Trim().ToString() == "REMARK")
            //        {
            //            dt.Columns[i].ColumnName = "备注";
            //        }

            //    }
            //    Session[key + "Body"] = dt;
            //    MessageBox.ResponseScript(Page, "top.MessageBox.Print({Value:\"ID=BASIC&VALUE=" + key + "\",Area:[\"800px\",\"500px\"],Scrollbar:true})");
            //}
            //catch (Exception)
            //{
            //    MessageBox.Show(Page, "请先点击查询！！");
            //}

            #endregion 打印1
        }

        /// <summary>
        /// 得到汇票银行
        /// </summary>
        public void BindBank()
        {
            int count;

            var dt = new Sys_BankBLL().GetEntitys(null, null, 0, 1000, out count);

            FORM_BANK_ID.DataSource = dt;
            FORM_BANK_ID.DataTextField = "C_NAME";
            FORM_BANK_ID.DataValueField = "N_ID";
            FORM_BANK_ID.DataBind();
            FORM_BANK_ID.Items.Insert(0, new ListItem("---请选择---", "-1"));

            FORM_BANK_ID.SelectedValue = "-1";
        }
    }
}